package com.chif.goingplus.aop.exception;

import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

//AOP实现
//该注解定义全局异常处理类
//@ControllerAdvice
//@ResponseBody
// 使用@RestControllerAdvice可以替代上面两个注解
@RestControllerAdvice
//@ControllerAdvice(basePackages ="com.example.demo.controller") 可指定包
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler{

    //自定义异常
    @ExceptionHandler(value=GlobalException.class) //该注解声明异常处理方法
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
        e.printStackTrace();
        // 在这里针对异常做自己的处理
        return  Result.error(ErrorCode.INTERNAL_SERVICE_ERROR);
    }


    //处理SQL异常
    @ExceptionHandler(value = BadSqlGrammarException.class)
    public Result<String> sqlException(BadSqlGrammarException badSqlGrammarException){
        badSqlGrammarException.printStackTrace();
        return Result.error(ErrorCode.BAD_SQL_GRAMMAR_ERROR);
    }

    //处理Controller异常
    @ExceptionHandler(value = Exception.class)
    public Result<String> handleException(Exception e){
        e.printStackTrace();
        return Result.error(ErrorCode.INTERNAL_SERVICE_ERROR);
    }


}
